﻿module Sustainalytics.GovernanceReports.Admin {

    import Common = Sustainalytics.Common;
    import CommonAdmin = Sustainalytics.Common.Admin;
    import Pager = Sustainalytics.Pager;
    import Routing = Sustainalytics.Routing;

    // News List controller
    export class CompanyViewController {

        // specifies whether current controller is in loading state
        public isLoading: boolean;

        // controller scope
        public $scope: ng.IScope;

        // services
        private $location: ng.ILocationService;
        private $routeParams: any;
        private governanceService: GovernanceService;
        private notificationFactory: Common.INotificationFactory;
        protected LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService;
        private $modal: IModal;
        private companyId: string;
        private selectedFile: any;
        public businessAndFinancialProfile: GovernancePdfProfileMetadata;
        public governanceDataProfile: GovernancePdfProfileMetadata;

        public companyProfile: GovernanceProfileDto;
        public companyName: string;
        public hasProfile: boolean;
        public hasBusinessAndFinancialProfile: boolean;
        public hasGovernanceDataProfile: boolean;

        // Ctor.
        constructor(
            $scope: ng.IScope,
            $location: ng.ILocationService,
            private RoutingService: Routing.IRoutingService,
            GovernanceService,
            notificationFactory: Common.INotificationFactory,
            $modal: IModal,
            LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService) {

            var ctx = this;

            $scope['governanceForCompany'] = ctx;

            ctx.$scope = $scope;
            ctx.$location = $location;
            ctx.$routeParams = RoutingService.getRouteParams();
            ctx.governanceService = GovernanceService;
            ctx.notificationFactory = notificationFactory;
            ctx.LongRunningTaskManagerService = LongRunningTaskManagerService;
            ctx.$modal = $modal;
            ctx.companyId = ctx.$routeParams['id'];

            // load all required data
            ctx.loadAllData();
        }

        private loadAllData() {
            this.getCompany();
            this.getCompanyPdfProfile();
            this.getCompanyProfileAndInsights();
        }

        public getCompany() {
            var ctx = this;
            ctx.isLoading = true;

            // get news items
            var companyProfilePromise: ng.IPromise<GovernanceProfileDto> = ctx.governanceService.getCompanyById(ctx.companyId);

            
            companyProfilePromise.then(corpData => {
                ctx.companyName = corpData['data'].companyName;                
            }, (error) => {
                    ctx.notificationFactory.error("Error on getting company profile.", error);
                });

            companyProfilePromise.finally(() => {
                ctx.isLoading = false;
            });
        }

        // get profile with insights
        public getCompanyProfileAndInsights() {
            var ctx = this;
            ctx.isLoading = true;

            // get news items
            var companyProfilePromise: ng.IPromise<GovernanceProfileDto> = ctx.governanceService.getCompanyProfileAndInsights(ctx.companyId);

            // on success set list of news
            companyProfilePromise.then(data => {
                if (data['data'].errorCode == 7000) {
                    ctx.hasProfile = false;    
                }
                else {
                    ctx.hasProfile = true;
                    ctx.companyProfile = data['data'];
                }
            }, error => {
                    ctx.notificationFactory.error('Error on getting company profile and insights.', error);
                });

            companyProfilePromise.finally(() => {
                ctx.isLoading = false;
            });
        }

        public getCompanyPdfProfile() {
            var ctx = this;
            ctx.isLoading = true;
            ctx.hasBusinessAndFinancialProfile = false;    
            ctx.hasGovernanceDataProfile = false;
            //get pd metadata items
            var companyProfilePromise: ng.IPromise<GovernancePdfProfileMetadata[]> = ctx.governanceService.getCompanyPdfProfile(ctx.companyId);
            
            // on success set metadata
            var successCallback = (pdfMetadata: GovernancePdfProfileMetadata[]) => {
                ctx.businessAndFinancialProfile = pdfMetadata.filter(el => (el.governancePdfType === GovernancePdfType.BusinessAndFinancialProfile))[0];
                if (ctx.businessAndFinancialProfile) {
                    if (ctx.businessAndFinancialProfile.updateOperationType !== 2) {
                        ctx.hasBusinessAndFinancialProfile = true;
                    }
                }
                ctx.governanceDataProfile = pdfMetadata.filter(el => (el.governancePdfType === GovernancePdfType.GovernanceDataProfile))[0];
                if (ctx.governanceDataProfile) {
                    if (ctx.governanceDataProfile.updateOperationType !== 2) {
                        ctx.hasGovernanceDataProfile = true;
                    }
                }
            };

            var errorCallback = error => {
                ctx.notificationFactory.error('Company pdf profile.', "Company pdf profile error");
            }

            companyProfilePromise.then(successCallback, errorCallback);

            companyProfilePromise.finally(() => {
                ctx.isLoading = false;
            });
        }
        // if isPdfProfile is false api/v1/filesclientplatform is called
        public downloadGovernanceInsightsPdfS3(insight: GovernanceInsightDto) {
            var ctx = this;
            var reportName = insight.title + "_" + ctx.companyName + "_" + moment().format("DD-MM-YYYY") + ".pdf"
            var data = { CompanyId: ctx.companyId, GovernancePdfType: GovernancePdfType.Insight, FileId: insight.fileId };
            ctx.LongRunningTaskManagerService.runTask(reportName,
                JSON.stringify(data),
                LRTM.LongRunningTaskTypeEnum.GovernancePDFS3, true, null);
        }

        public downloadGovernancePdfS3(profile: GovernancePdfProfileMetadata) {
            var ctx = this;
            var reportName = profile.corporateGovernancePdfProfileString + "_" + ctx.companyName + "_" + moment().format("DD-MM-YYYY") + ".pdf"
            var data = { CompanyId: ctx.companyId, GovernancePdfType: profile.governancePdfType };
            ctx.LongRunningTaskManagerService.runTask(reportName,
                JSON.stringify(data),
                LRTM.LongRunningTaskTypeEnum.GovernancePDFS3, true, null);
        }

        public downloadGovernanceFileEnabled(fileId: string, fileName: string): boolean {
            var ctx = this;
            var result = false;

            if (fileId != undefined && fileName != undefined) {
                result = true;
            }
            return result;
        }

        // delete selected pdf profile
        public deletePdfProfile(companyProfile) {
            var ctx = this;
            var modalInstanceDelete = ctx.$modal.open({
                templateUrl: 'Views/GovernanceReports/governance_report_deleteProfile.tpl.html',
                controller: 'DeleteCheckController',
                size: 'lg',
                backdrop: 'static'
            });
            modalInstanceDelete.result.then((out) => {
                if (out['deleteCheck'] == true) {
                    ctx.companyProfile = new GovernanceProfileDto();
                    // delete pdf file
                    var deleteProfilePromise: ng.IPromise<GovernanceProfileDto> = ctx.governanceService.deletePdfProfile(companyProfile.companyId, companyProfile.governancePdfType);
                    deleteProfilePromise.then(() => {
                       
                    });

                    deleteProfilePromise.finally(() => {
                       ctx.loadAllData();
                    });
                }
            });
        }

        // switch to add insight mode
        public addInsight() {
            var ctx = this;
            var modalInstance = ctx.$modal.open(
                {
                    templateUrl: 'Views/GovernanceReports/governance_reports_insightAdd.tpl.html',
                    controller: 'InsightAddController',
                    size: 'lg',
                    backdrop: 'static',
                    resolve:
                    {
                        currentInsight() {
                            return null;
                        },
                        companyProfile() {
                            return ctx.companyProfile;
                        },
                        companyName() {
                            return ctx.companyName;
                        }
                    }
                });

            modalInstance.result.then((out) => {
                ctx.companyProfile = out['companyProfile'];
            });
        }

        // switch to edit news mode
        public editInsight(insight: GovernanceInsightDto) {
            var ctx = this;
            var modalInstance = ctx.$modal.open(
                {
                    templateUrl: 'Views/GovernanceReports/governance_reports_insightAdd.tpl.html',
                    controller: 'InsightAddController',
                    size: 'lg',
                    backdrop: 'static',
                    resolve:
                    {
                        currentInsight() {
                            return insight;
                        },
                        companyProfile() {
                            return ctx.companyProfile;
                        },
                        companyName() {
                            return ctx.companyName;
                        }
                    }
                });

            modalInstance.result.then((out) => {
                ctx.getCompanyProfileAndInsights();
            });
        }

        // delete selected insight
        public deleteInsight(insight: GovernanceInsightDto) {
            var ctx = this;

            var modalInstanceDelete = ctx.$modal.open({
                templateUrl: 'Views/GovernanceReports/governance_report_deleteInsight.tpl.html',
                controller: 'DeleteCheckController',
                size: 'lg',
                backdrop: 'static'
            });

            modalInstanceDelete.result.then((out) => {
                if (out['deleteCheck'] == true) {
                    //list of insights without the insight that we want to delete
                    var newInsights = ctx.companyProfile.insights
                        .filter(el => (el.id !== insight.id));

                    ctx.companyProfile.insights = newInsights;
   
                    // delete insight
                    var deleteInsightPromise: ng.IPromise<GovernanceProfileDto> = ctx.governanceService.deleteInsight(ctx.companyProfile.id, insight.fileId);

                    deleteInsightPromise.then(function () {
                    });
                }
            });
        }
       
        public onSelectPdf(files, pdfProfile): any {
            var ctx = this;
           
            var file = files[0]; // html assures is just 1
            if (file) {
                if (file.size > 10 * 1024 * 1024) {
                    ctx.notificationFactory.error('File size.', "Selected file is too large");
                }
                else if (file.type !== "application/pdf") {
                    ctx.notificationFactory.error('Wrong file type.', "Selected file must be a pdf file");
                }
                else {
                    ctx.selectedFile = file;
                    var promise = ctx.governanceService.fileUploadReportFile(ctx.selectedFile, ctx.companyId.replace(" ", ""), pdfProfile, null);
                    promise.then(
                        //success
                        (data: { filename: string }) => {
                            //create pdf metadata
                            var corporateGovernanceFileDto = new GovernancePdfProfileMetadata();
                            //corporateGovernanceFileDto.fileUrl = data.fileUrl;
                            corporateGovernanceFileDto.fileName = data.filename;
                            //corporateGovernanceFileDto.fileId = data.id;
                            corporateGovernanceFileDto.companyId = ctx.companyId;
                            corporateGovernanceFileDto.governancePdfType = pdfProfile;
                            //save pdf metadata
                            var promiseMetadata = ctx.governanceService.savePfdBusinessProfileMetadata(corporateGovernanceFileDto);
                            promiseMetadata.then(
                                //success
                                () => {
                                    ctx.loadAllData();
                                    ctx.notificationFactory.success('Upload succeeded.');
                                },
                                //error
                                () => {
                                    ctx.notificationFactory.error('Upload failed.', "Upload failed for pdf metadata");
                                }
                            );
                        },
                        //error
                        () => {
                            ctx.notificationFactory.error('Upload failed.', "Upload failed for pdf file");
                        }
                        );
                }
            }
        }
    }

    // register controller with News Angular module
    var mod = angular.module(governanceAdminReportsModuleName);
    
    mod.controller('CompanyViewController',
        ['$scope', '$location', 'RoutingService', 'GovernanceService', 'notificationFactory', '$modal', 'LongRunningTaskManagerService', CompanyViewController]);
      
}